import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import ProTable, {ProTableProps} from "@ant-design/pro-table";
import {SysDictValueData, SysDictValueParams, SysDictValueAdd} from "@/pages/system/dict/value/type";
import columns from "@/pages/system/dict/value/list/config/columns";
import {Button, message, Space} from "antd";
import React, {useRef, useState} from "react";
import {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadSysDictValueExport,
  downloadSysDictValueExportTemplate,
  sysDictValueImport,
  sysDictValueUpdate,
  sysDictValueAdd,
  sysDictValuePageList,
  sysDictValueRemove
} from "@/services/system/dict/value/api";
import {history} from "umi";
import {OptionActions} from "@/type/type";
import Upload from "@/components/Upload";
import AddSysDictValue from "@/pages/system/dict/value/list/components/AddSysDictValue";
import {ProFormInstance} from "@ant-design/pro-form";
import {downloadDictCode} from "@/services/gen/api";
import {CModalFormProps} from "@/components/CModalForm/type";
import CModalForm from "@/components/CModalForm";
import generateEnumItemList from "@/pages/system/dict/value/list/config/fields";


export default () => {

  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number | string)[]>([]);
  // @ts-ignore
  const dictTypeId: number = history?.location?.query?.dictTypeId;
  const enum_: any = history?.location?.query?.enum_;
  const sysDictValueAddRef: React.MutableRefObject<ProFormInstance<SysDictValueAdd> | undefined> = useRef<ProFormInstance<SysDictValueAdd> | undefined>();
  const generateEnumRef: React.MutableRefObject<ProFormInstance<{ download: boolean, groupId: string }> | undefined> = useRef<ProFormInstance<{ download: boolean, groupId: string }> | undefined>();
  const optionAction: OptionActions<SysDictValueAdd, SysDictValueData> & { generateEnumModal: CModalFormProps<{ download: boolean, groupId: string }>, enum_: boolean } = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        sysDictValueImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(data) {
      // @ts-ignore
      sysDictValueUpdate(data as SysDictValueAdd).then(res => {
        message.success("操作成功").then()
        actionRef.current?.reload()
      })
    },
    editModal: (data: SysDictValueData) => {
      return {
        trigger: <Button type="link" onClick={() => {
          sysDictValueAddRef.current?.setFieldsValue(data)
        }}>编辑</Button>,
        onFinish: async (formData) => {
          console.log(formData)
          await sysDictValueAddRef.current?.validateFields().then(res => {
            const sysDictValue: any = {
              ...formData,
              id: data.id
            }
            sysDictValueUpdate(sysDictValue).then(res => {
              sysDictValueAddRef.current?.resetFields();
              message.success("操作成功")
              actionRef.current?.reload();
            })
          })
          return true
        },
        title: "编辑字典值",
        formRef: sysDictValueAddRef,
      }
    },
    add() {
      history.push({
        pathname: "sys/dict/value/add"
      })
    },
    addModal: {
      trigger: <Button type="primary" onClick={() => sysDictValueAddRef.current?.resetFields()}>新增</Button>,
      onFinish: async (formData) => {
        await sysDictValueAddRef.current?.validateFields().then(res => {
          // @ts-ignore
          const data: SysDictValueAdd = {
            ...formData,
            dictTypeId: dictTypeId
          }
          sysDictValueAdd(data).then(res => {
            message.success("新增成功")
            sysDictValueAddRef.current?.resetFields();
            actionRef.current?.reload();
          })
        })
        return true
      },
      // layout: "horizontal",
      title: "新增字典值",
      formRef: sysDictValueAddRef,
    },
    export() {
      downloadSysDictValueExport({ids: selectedRowKeys, id: dictTypeId}).then(res => {
        message.success("导出成功").then(res => {
        })
        setSelectedRowKeys([]);

      })
    },
    remove(ids) {
      sysDictValueRemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    exportTemplate() {
      downloadSysDictValueExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    },
    generateEnumModal: {
      trigger: <Button type={"primary"}>生成代码</Button>,
      onFinish: async (formData) => {
        return await downloadDictCode({...formData, id: dictTypeId, enum_: enum_}).then(res => {
          message.success("生成成功").then()
          generateEnumRef.current?.setFieldValue("download", false)
          return true;
        })
      },
      layout: "horizontal",
      width: 500,
      title: "配置",
      groupList: generateEnumItemList,
      formRef: generateEnumRef,
    },
    enum_: enum_
  }

// @ts-ignore
  const tableProps
    :
    ProTableProps<SysDictValueData, SysDictValueParams> = {
    rowSelection: {
      // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      // selections: [],
    },
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys);
      return (
        <Space size={24}>
                      <span>
                          已选 {selectedRowKeys.length} 项
                          <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                           取消选择
                         </a>
                      </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove([])}>批量删除</a>
          <a onClick={() => optionAction.export()}>导出数据</a>
        </Space>
      );
    },
    pagination: {
      defaultPageSize: 10
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    // @ts-ignore
    columns: columns(optionAction),
    request: async (params, sort, filter) => {
      const sysDictValueParams: SysDictValueParams = {
        pageNum: params.current as number,
        pageSize: params.pageSize,
        label: params.label,
        dictTypeId
      };
      return await sysDictValuePageList(sysDictValueParams).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        <AddSysDictValue enum_={enum_} {...optionAction.addModal}/>
        <Upload {...optionAction.import}>
          <Button type="primary">导入</Button>
        </Upload>
        <Button type="primary" onClick={() => optionAction.export()}>导出</Button>
        <Button type="primary" onClick={() => optionAction.exportTemplate()}>导出模版</Button>
        <CModalForm {...optionAction.generateEnumModal}/>
      </Space>
    ),
    actionRef
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<SysDictValueData, SysDictValueParams> {...tableProps}>
        </ProTable>
      </ProCard>
    </PageContainer>
  )
}
